// pages/open_info/open_info.js
const app = getApp()
var util = require('../../utils/util.js');
var aliyun_api = require('../../utils/aliyun-api-gateway.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    LockState: app.globalData.deviceInfo.LockState,
    BatteryPercentage: app.globalData.deviceInfo.BatteryPercentage,
    SN: app.globalData.deviceInfo.SN,
    Volume: app.globalData.deviceInfo.Volume,
    Volume1: app.globalData.deviceInfo.Volume,
    isVolume:false,
    userInfo: {},
    id: 'api',
    info: null,
    userListInfo: [
      {
        icon: '',
        text: '门锁状态',
        usedNum: 0,
        totalNum: 20,
        detailInfo: [],
        isSpace: false,
        isArrow: false,
        isSwitch: false,
        isChecked: false,
        isunread: false,
        unreadNum: 1,
        isText: true,
        content: app.globalData.deviceInfo.LockState,
        isNum:false
      }, {
        icon: '',
        text: '电池电量',
        usedNum: 0,
        totalNum: 20,
        detailInfo: [],
        isSpace: false,
        isArrow: false,
        isSwitch: false,
        isChecked: false,
        isunread: false,
        unreadNum: 1,
        isText: true,
        content: `${app.globalData.deviceInfo.BatteryPercentage}%`,
        isNum: false,
        isClick:false
      }, {
        icon: '',
        text: '门锁SN',
        usedNum: 0,
        totalNum: 20,
        detailInfo: [],
        isSpace: false,
        isArrow: false,
        isSwitch: false,
        isChecked: false,
        isunread: false,
        unreadNum: 1,
        isText: true,
        content: app.globalData.deviceInfo.SN,
        isNum: false,
        isClick: false
      }, {
        icon: '',
        text: '门锁音量',
        usedNum: 0,
        totalNum: 20,
        detailInfo: [],
        isSpace: true,
        isArrow: false,
        isSwitch: false,
        isChecked: false,
        isunread: false,
        unreadNum: 1,
        isText: true,
        content: app.globalData.deviceInfo.Volume,
        isNum: false,
        isClick: true
      }]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var data = app.globalData.kvStorage
    that.setData({
      info: data.deviceList[options.index]
    })
  //  that.UpdateDevInfo();
    that.UpdateInfo()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
  //  that.UpdateDevInfo()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this
    that.UpdateInfo()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 弹出框蒙层截断touchmove事件
   */
  preventTouchMove: function () {},

  /**
   * radio change事件
   */
  radioChange: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    if (index > 4)
    {
      return;
    }
    
    var list = "userListInfo["+index+"].isChecked";
    for (var i = 0; i < that.data.userListInfo.length; i++) {
      that.data.userListInfo[i].isChecked = false;
    }
    that.setData({
      userListInfo:that.data.userListInfo,
      [list]:true
    })
  },

  OpenDetailInfo: function (e) {

    var index = e.currentTarget.dataset.index
    if(index >=4){
      wx.navigateTo({
        //  url: './detailInfo/detailInfo?list=' + JSON.stringify(app.globalData.deviceInfo[index]) + '&text=' + title[index]
        url: './detailInfo/detailInfo?index=' + (index - 4)
      })
    }
    else if(index == 3){
      this.setData({
        isVolume: true,
        Volume1:this.data.Volume
      });
    }
  },

  UpdateDevInfo: function () {
    var that = this
    var tmpdevInfo = wx.getStorageSync('deviceInfo')
  //  console.log('open_info', tmpdevInfo)
    var tmpUserList = that.data.userListInfo
    for (let i = 0; i < tmpUserList.length; i++) {
      tmpUserList[i+4].usedNum = tmpdevInfo.deviceInfo[i].usedNum;
      tmpUserList[i+4].totalNum = tmpdevInfo.deviceInfo[i].totalNum;
      tmpUserList[i+4].detailInfo = tmpdevInfo.deviceInfo[i].detailInfo;
    }
    that.setData({
      userListInfo: tmpUserList
    })
  },

  UpdateInfo: function () {
    var that = this
    that.getLockState()
    .then(that.getBatteryPercentage)
    .then(that.getVolume)
    .then(that.getSN)
    .then(function () {
      wx.stopPullDownRefresh()
    });
  },
  /***************************调整音量弹窗**************************/
  volumeChange:function(e){
    var that = this;
    that.setData ({Volume1:e.detail.value});
  },
  confirm:function(){ 
    var that = this;
    // app.globalData.deviceInfo.Volume = that.data.Volume1;
    that.setVolume(that.data.Volume1);
    
    
  },
  cancle:function(){
    var that = this;
    that.setData({isVolume:false});
  },
  /***************************获取门锁状态**************************/
  getLockState: function () {
    var that = this;
    const params = {
      url: 'https://api.link.aliyun.com/thing/device/property/query',
      apiVer: '1.1.2',
      param: {
        // 接口参数
        "productKey": that.data.info.productKey,
        "deviceName": that.data.info.deviceName,
        "propertyIdentifier":"LockState"
      }
    }
    return new Promise(function (resolve, reject) {
      aliyun_api.request(params).then(function (res) {
        var value = res.data.value
        if (value==0){
          that.setData({LockState:"关"});
          app.globalData.deviceInfo.LockState = "关";
        }
        else{
          that.setData({ LockState: "开" });
          app.globalData.deviceInfo.LockState = "开";
        }
        that.setData({ 'userListInfo[0].content': that.data.LockState})
        resolve()
      })
    })
  },
  /***************************获取电池电量**************************/
  getBatteryPercentage: function () {
    var that = this;
    const params = {
      url: 'https://api.link.aliyun.com/thing/device/property/query',
      apiVer: '1.1.2',
      param: {
        // 接口参数
        "productKey": that.data.info.productKey,
        "deviceName": that.data.info.deviceName,
        "propertyIdentifier": "BatteryPercentage"
      }
    }
    return new Promise(function (resolve, reject) {
      aliyun_api.request(params).then(function (res) {
        var value = res.data.value
        that.setData({ BatteryPercentage: value });
        app.globalData.deviceInfo.BatteryPercentage = value;
        that.setData({ 'userListInfo[1].content': `${value}%`})
        resolve()
      })
    })
  },
  /***************************获取门锁音量**************************/
  getVolume: function () {
    var that = this;
    const params = {
      url: 'https://api.link.aliyun.com/thing/device/property/query',
      apiVer: '1.1.2',
      param: {
        // 接口参数
        "productKey": that.data.info.productKey,
        "deviceName": that.data.info.deviceName,
        "propertyIdentifier": "Volume"
      }
    }
    return new Promise(function (resolve, reject) {
      aliyun_api.request(params).then(function (res) {
        var value = res.data.value
        that.setData({ Volume: value });
        app.globalData.deviceInfo.Volume = value;
        that.setData({ 'userListInfo[3].content': value })
        resolve(value)
      })
    })
  },
  /***************************获取门锁SN**************************/
  getSN: function () {
    var that = this;
    const params = {
      url: 'https://api.link.aliyun.com/thing/device/property/query',
      apiVer: '1.1.2',
      param: {
        // 接口参数
        "productKey": that.data.info.productKey,
        "deviceName": that.data.info.deviceName,
        "propertyIdentifier": "SN"
      }
    }
    return new Promise(function (resolve, reject) {
      aliyun_api.request(params).then(function (res) {
        var value = res.data.value
        that.setData({ SN: value });
        app.globalData.deviceInfo.SN = value;
        that.setData({ 'userListInfo[2].content': value })
        resolve()
      })
    })
  },
  /***************************设置门锁音量**************************/
  setVolume: function (value) {
    var that = this;
    const params = {
      url: 'https://api.link.aliyun.com/thing/device/properties/set',
      apiVer: '1.1.2',
      param: {
        // 接口参数
        "productKey": that.data.info.productKey,
        "deviceName": that.data.info.deviceName,
        "properties": {"Volume":value}
      }
    }
    util.NetStatusOk().then(function () {
    aliyun_api.request(params).then(function (res) {
      wx.showLoading({
        title: '正在设置',
      })
      setTimeout(function(){
        wx.hideLoading();
          that.getVolume().then(function (result) {
          // console.log(result)
          if(result == value){
            wx.showToast({
              title: '设置成功',
              icon: 'success',
              duration: 1000
            })
            that.setData({
              isVolume: false,
              Volume: that.data.Volume1,
              'userListInfo[3].content': that.data.Volume1
            });
          }
          else{
            wx.showToast({
              title: '设置失败',
              duration: 1000,
              image: '/images/fail.png'
            })
          }
        })
      },2000)
      
    })
    .catch(function(){
      wx.showToast({
        title: '设置失败',
        duration: 1000,
        image: '/images/fail.png'
      })
    })
    })
  },

})